import paho.mqtt.client as mqtt
import threading
import logging


class MQTTClientWrapper:
    def __init__(self, config, sensor_data):
        self.config = config
        self.sensor_data = sensor_data
        self.is_connected = False
        self.client = None
        self.lock = threading.Lock()

        # 配置日志
        self.logger = logging.getLogger("MQTTClient")

        # 初始化MQTT客户端
        self._init_client()

    def _init_client(self):
        try:
            self.client = mqtt.Client(client_id=self.config["client_id"])
            self.client.on_connect = self._on_connect
            self.client.on_disconnect = self._on_disconnect
            self.client.on_message = self._on_message

            # 设置连接超时
            self.client.reconnect_delay_set(min_delay=1, max_delay=120)

            # 连接MQTT服务器
            self.client.connect(self.config["broker"], self.config["port"], 60)

            # 启动MQTT客户端线程
            mqtt_thread = threading.Thread(target=self.client.loop_forever)
            mqtt_thread.daemon = True
            mqtt_thread.start()

            self.logger.info("MQTT客户端已启动")
        except Exception as e:
            self.logger.error(f"初始化MQTT客户端时发生错误: {str(e)}")

    # 连接中断回调函数
    def _on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            self.logger.info(f"MQTT Connected successfully")
            self.is_connected = True
            client.subscribe(self.config["topic"])
        else:
            self.logger.error(f"MQTT Connection failed with code {rc}")
            self.is_connected = False

    def _on_disconnect(self, client, userdata, rc):
        self.logger.warning(f"MQTT Disconnected with code {rc}")
        self.is_connected = False
        # 尝试重连
        self._reconnect()

    def _on_message(self, client, userdata, msg):
        payload = msg.payload.decode("utf-8")
        self.logger.info(f"收到MQTT消息: {payload}")

        if hasattr(self, "handle_mqtt_message"):
            self.handle_mqtt_message(payload)

    def _reconnect(self):
        try:
            if not self.is_connected:
                self.logger.info("尝试重新连接MQTT服务器...")
                self.client.reconnect()
                # 给连接一些时间
                import time

                time.sleep(1)
                if self.client.is_connected():
                    self.is_connected = True
                    self.logger.info("MQTT重新连接成功")
                    return True
                else:
                    self.logger.warning("MQTT重新连接失败")
                    return False
            return True
        except Exception as e:
            self.logger.error(f"重连时发生错误: {str(e)}")
            return False

    def publish_control_message(self, command):
        try:
            with self.lock:
                if not self.is_connected:
                    self.logger.warning("MQTT未连接，尝试重连")
                    self._reconnect()
                    if not self.is_connected:
                        self.logger.error("发布前重连失败")
                        return False

                # 发布控制命令到MQTT
                result = self.client.publish(self.config["control_topic"], command)
                status = result[0]
                if status == 0:
                    self.logger.info(
                        f"成功发送控制命令: {command} 到主题 {self.config['control_topic']}"
                    )
                    return True
                else:
                    self.logger.error(f"发送控制命令失败，状态码: {status}")
                    return False
        except Exception as e:
            self.logger.error(f"发送控制命令时发生错误: {str(e)}")
            return False
